
package com.ronglian.register_mini_program.controller;

import com.ronglian.register_mini_program.model.RecommendImgWithBLOBs;
import com.ronglian.register_mini_program.model.RegisterUser;
import com.ronglian.register_mini_program.result.ResultBody;
import com.ronglian.register_mini_program.service.RecommendService;
import com.ronglian.register_mini_program.service.UserService;
import com.ronglian.register_mini_program.util.FtpUtil;
import com.ronglian.register_mini_program.util.OSUtil;
import io.swagger.annotations.*;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.util.List;
import javax.servlet.http.HttpServletRequest;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

@RestController
@RequestMapping({"/file"})
@Api(tags = {"文件操作"}, description = "文件操作")
@ApiResponses({@ApiResponse(code = 200, message = "Successful — 请求已完成"),
        @ApiResponse(code = 400, message = "请求中有语法问题，或不能满足请求"),
        @ApiResponse(code = 401, message = "未授权客户机访问数据"),
        @ApiResponse(code = 404, message = "服务器找不到给定的资源；文档不存在"),
        @ApiResponse(code = 500, message = "服务器不能完成请求")})
public class FileController {
    @Autowired
    UserService userService;
    @Autowired
    RecommendService recommendService;

    public FileController() {
    }

    @ApiOperation(value = "ftp方式文件上传", notes = "ftp方式文件上传")
    @RequestMapping(value = {"/ftpUpload"}, method = {RequestMethod.POST})
    @ApiImplicitParams({@ApiImplicitParam(paramType = "query", dataType = "MultipartFile", name = "file", value = "上传文件", required = true),
            @ApiImplicitParam(paramType = "query", dataType = "String", name = "open_id", value = "微信唯一标识", required = true)})
    public ResultBody ftpUpload(@RequestParam("file") MultipartFile file, @RequestParam("openid") String openid, HttpServletRequest request) throws IOException {

        try {

            String fileName = file.getOriginalFilename();
            InputStream inputStream = file.getInputStream();
            String filePath = null;
            Boolean flag = FtpUtil.uploadFile(fileName, inputStream);
            if (flag) {
                System.out.println("ftp上传成功！");
                filePath = fileName;
            }

            RegisterUser user = this.userService.findByOpenId(openid);
            if (user != null) {
                user.setHead_image_url(filePath);
                this.userService.update(user);
            }

            return new ResultBody();
        } catch (Exception e) {
            e.printStackTrace();
            return new ResultBody("500", "ftp方式文件上传失败！");
        }


    }

    @ApiOperation(value = "获取推荐的图片列表", notes = "获取推荐的图片列表")
    @RequestMapping(value = {"/selectRecommendImgList"}, method = {RequestMethod.GET})
    public ResultBody selectRecommendImgList() {

        try {

            List<RecommendImgWithBLOBs> recommendImgs = this.recommendService.getAllRecommendImgList();
            if (recommendImgs == null) {
                return new ResultBody("500", "获取推荐的图片列表为空！");
            } else {
                return new ResultBody(recommendImgs);
            }
        } catch (Exception e) {
            e.printStackTrace();
            return new ResultBody("500", "获取推荐的图片列表失败！");
        }

    }

    @ApiOperation(value = "图片上传", notes = "图片上传")
    @ApiImplicitParams({@ApiImplicitParam(paramType = "query", dataType = "MultipartFile", name = "uploadfile", value = "上传的图片", required = true),
            @ApiImplicitParam(paramType = "query", dataType = "String", name = "open_id", value = "微信唯一标识", required = true)})
    @RequestMapping(value = "/pictureUpload", method = RequestMethod.POST)
    public ResultBody pictureUpload(@RequestParam("open_id") String open_id, MultipartFile uploadfile, HttpServletRequest request) throws IllegalStateException, IOException {

        try {


            if (uploadfile != null) {
                String path = "";
                String type = "";
                //每个用户都有自己的文件夹
                RegisterUser user = userService.findByOpenId(open_id);
                if (user == null) {
                    return new ResultBody("500", "请先获取用户授权");
                }

                //源文件的名称
                String fileName = uploadfile.getOriginalFilename();
                System.out.println("上传的文件原名称:" + fileName);
                type = fileName.indexOf(".") != -1 ? fileName.substring(fileName.lastIndexOf(".") + 1, fileName.length()) : null;
                if (type != null) {
                    if (!"GIF".equals(type.toUpperCase()) && !"PNG".equals(type.toUpperCase()) && !"JPG".equals(type.toUpperCase())) {
                        System.out.println("不是我们想要的文件类型,请按要求重新上传");
                        return new ResultBody("500", "文件类型错误");
                    } else {
                        String realPath = null;
                        if (OSUtil.isWindows()) {
                            realPath = "D:\\uploadPth\\";
                        }

                        if (OSUtil.isLinux()) {
                            //图片上传路径 /ftp/images/
                            realPath = "/ftp/images/";
                        }

                        String trueFileName = System.currentTimeMillis() + uploadfile.getOriginalFilename().substring(fileName.lastIndexOf("."));
                        path = realPath + user.getUid();

                        ///ftp/images/{uid}/245554555555.jpg
                        File file = new File(path);
                        if (!file.exists()) {
                            file.mkdirs();
                            file.setExecutable(true);
                            file.setReadable(true);
                            file.setWritable(true);
                        }
//                    String[] files = new String[]{
//                            trueFileName
//                    };
//                    List<String> list = ImageUtil.generateThumbnail2Directory(path, files);


                        path += File.separator + trueFileName;
                        System.out.println("存放文件的路径:" + path);
                        File destinationDir = new File(path);
                        uploadfile.transferTo(destinationDir);
                        if (destinationDir.exists()) {
                            destinationDir.setExecutable(true);
                            destinationDir.setReadable(true);
                            destinationDir.setWritable(true);
                        }

//                    Thumbnails.of(uploadfile.getInputStream()).scale(0.25f).outputQuality(0.25f).toFiles(destinationDir, Rename.PREFIX_DOT_THUMBNAIL);
                        System.out.println("文件成功上传到指定目录下");
                        return new ResultBody(path);
                    }
                } else {
                    System.out.println("文件类型为空");
                    return new ResultBody("500", "文件类型为空");
                }
            } else {
                System.out.println("没有找到相对应的文件");
                return new ResultBody("500", "没有找到相对应的文件");
            }
        } catch (Exception e) {
            e.printStackTrace();
            return new ResultBody("500", "图片上传失败！");
        }


    }

    @ApiOperation(value = "批量图片上传", notes = "批量图片上传")
    @ApiImplicitParams({@ApiImplicitParam(paramType = "query", dataType = "MultipartFile", name = "uploadfile", value = "上传的图片", required = true),
            @ApiImplicitParam(paramType = "query", dataType = "String", name = "open_id", value = "微信唯一标识", required = true)})
    @RequestMapping(value = "/multiPictureUpload", method = RequestMethod.POST)
    public ResultBody multiPictureUpload(@RequestParam("open_id") String open_id, MultipartFile[] uploadfile, HttpServletRequest request) throws IllegalStateException, IOException {

        try {

            String path = "";
            if (uploadfile != null) {

                String type = "";

                //每个用户都有自己的文件夹
                RegisterUser user = userService.findByOpenId(open_id);
                if (user == null) {
                    return new ResultBody("500", "请先获取用户授权");
                }

                if (uploadfile == null || uploadfile.length <= 0) {
                    return new ResultBody("500", "请选择上传文件！");
                }
                for (int i = 0; i < uploadfile.length; i++) {
                    ResultBody resultBody = pictureUpload(open_id, uploadfile[i], request);
                    String result = resultBody.getResult().toString();
                    if (result != null) {
                        path += result + ";";
                    }
                }

            }
            return new ResultBody(path);
        } catch (Exception e) {
            e.printStackTrace();
            return new ResultBody("500", "批量图片上传失败！");
        }


    }

    @ApiOperation(value = "删除图片", notes = "删除图片")
    @ApiImplicitParam(paramType = "query", dataType = "String", name = "picturePath", value = "图片路径", required = true)
    @RequestMapping(value = "/delPicture", method = RequestMethod.POST)
    public ResultBody delPicture(@RequestParam("picturePath") String picturePath) {

        try {

            String resultInfo = "";
//        int lastIndexOf = picturePath.lastIndexOf("/");
//        String sb = picturePath.substring(lastIndexOf + 1, picturePath.length());
            String realPath = "";
            String sl_realPath = "";
            if (OSUtil.isWindows()) {
                realPath = "D:\\uploadPth\\" + picturePath;
            }

            if (OSUtil.isLinux()) {
                //图片上传路径 /ftp/images/
                realPath = "/ftp/images/" + picturePath;
            }
            File file = new File(realPath);
            File file2 = new File(sl_realPath);
            if (file.exists()) {
                if (file.delete()) {
                    resultInfo = "删除成功";
                } else {
                    return new ResultBody("500", "删除失败！");
                }
//            if ()
            } else {
                return new ResultBody("500", "文件不存在！");
            }

            return new ResultBody(resultInfo);
        } catch (Exception e) {
            e.printStackTrace();
            return new ResultBody("500", "删除图片失败！");
        }


    }

}
